/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pkdl.tables;

import java.util.Comparator;
import java.util.Vector;

public class ColumnSorterByName implements Comparator {

	int colIndex;
	boolean ascending;

	ColumnSorterByName(int colIndex, boolean ascending) {
		this.colIndex = colIndex;
		this.ascending = ascending;
	}

	public int compare(Object a, Object b) {
		Vector v1 = (Vector) a;
		Vector v2 = (Vector) b;
		Object o1 = v1.get(this.colIndex);
		Object o2 = v2.get(this.colIndex);

		// Treat empty strains like nulls
		if (o1 instanceof String && ((String) o1) == null) {
			o1 = null;
		}
		if (o2 instanceof String && ((String) o2) == null) {
			o2 = null;
		}

		// Sort nulls so they appear last, regardless
		// of sort order
		if (o1 == null && o2 == null) {
			return 0;
		} else if (o1 == null) {
			return 1;
		} else if (o2 == null) {
			return -1;
		} else if (o1 instanceof Comparable) {
			if (this.ascending) {
				return ((String) o1).toUpperCase().compareTo(
						((String) o2).toUpperCase());
			} else {
				return ((String) o2).toUpperCase().compareTo(
						((String) o1).toUpperCase());
			}
		} else {
			if (this.ascending) {
				return ((String) o1).toUpperCase().compareTo(
						((String) o2).toUpperCase());
			} else {
				return ((String) o2).toUpperCase().compareTo(
						((String) o1).toUpperCase());
			}
		}
	}
}
